package core

import "strings"

type node struct {
	children map[string]*node
	handler  HandlerFunc
}

type Router struct {
	trees map[string]*node
}

func NewRouter() *Router {
	return &Router{trees: make(map[string]*node)}
}

func (r *Router) AddRoute(method, path string, handler HandlerFunc) {
	if r.trees[method] == nil {
		r.trees[method] = &node{children: make(map[string]*node)}
	}
	parts := strings.Split(strings.Trim(path, "/"), "/")
	current := r.trees[method]

	for _, part := range parts {
		if current.children[part] == nil {
			current.children[part] = &node{children: make(map[string]*node)}
		}
		current = current.children[part]
	}
	current.handler = handler
}

func (r *Router) Handle(ctx *Context) bool {
	if tree := r.trees[ctx.Method()]; tree != nil {
		parts := strings.Split(strings.Trim(ctx.Path(), "/"), "/")
		current := tree

		for _, part := range parts {
			if current.children[part] == nil {
				return false
			}
			current = current.children[part]
		}

		if current.handler != nil {
			current.handler(ctx)
			return true
		}
	}
	ctx.JSON(404, map[string]string{"error": "Not Found"})
	return false
}
